# 要添加一个新单元，输入 '# %%'
# 要添加一个新的标记单元，输入 '# %% [markdown]'
# %%
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

# %%
import hashlib
import os
import datetime

def GetFileMd5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = open(filename,'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()

# %%
import sqlite3

conn = sqlite3.connect('wallpaper.db')
cur = conn.cursor()


# %%
from pathlib import Path


def init_data(p):
    ''' 第一次才运行,初始化原始数据 '''
    try:
        cur.execute("""CREATE TABLE wallpapers ( id INT PRIMARY KEY, filename TEXT, md5 TEXT, Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);""")
    except:
        cur.execute("select count(*) from wallpapers")
        count = cur.fetchone()[0]
        print(f"wallpapers 已为您记录{count}条数据")
        return

    datalist = []
    for x in list(p.glob('*.jpg')):        
        md5 = GetFileMd5(x)
        print(f"{x}:{md5}")
        datalist.append(tuple((str(x),md5)) )

    insert_table_wallpapers(datalist)  # 第一次才运行


def insert_table_wallpapers(datalist):
    cur.executemany("INSERT INTO wallpapers (filename,md5)  VALUES(?, ?);", datalist)
    print(f"插入数据量: {cur.rowcount}")
    conn.commit()

def search_table(filename,md5):
    cur.execute("select * from wallpapers where md5 = ? ", [md5])  # SQL的 params 参数必须是一个数组
    row = cur.fetchone()
    # print(row)
    if row:
        old_filename = row[1]
        old_time = row[3]
        print(f"旧文件:{filename}{md5} 已存在名为 {old_filename} 的文件 加入日期:{old_time}") 
        return True
    else:
        print(f"新文件:{filename}{md5} 是一个新文件") 
        return False  


# %%

def get_max_filename_num(destination_path):
    p = destination_path    
    digits = []
    for x in list(p.glob('*.jpg')):
        isdigit_str = str(x.name).split(".")[0]
        if isdigit_str.isdigit():
            digits.append(int(isdigit_str))
    max_num = max(digits) + 1
    return str(max_num) + ".jpg"


# %%
import shutil 

if __name__ == "__main__":

    # new_file_name = get_max_filename_num()
    # print(new_file_name)

    source_path = Path(r'C:\Users\yulike\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\.')
    destination_path = Path(r'D:\锁屏壁纸\.')

    init_data(destination_path)


    for x in list(source_path.glob('*')):
        md5 = GetFileMd5(x)
        print(f"{x.name}:{md5}")

        if not search_table(x.name,md5) :
            old_file = str(x)
            new_file = str(destination_path / get_max_filename_num(destination_path)) # 斜杠 / 操作符有助于创建子路径
            print(f"{old_file} => {new_file}")
            insert_table_wallpapers([(new_file,md5)])
            shutil.copyfile(old_file,new_file)

    X=input("按任意键退出")
    